{% extends 'base.html' %}

{% set current_menu = 'project' %}
{% set current_page = 'project_list' %}

{% block title %}项目详情 - 项目管理系统{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="https://cdn.dhtmlx.com/gantt/edge/dhtmlxgantt.css">
<style>
    .gantt_container {
        height: 765px;
        width: 100%;
        min-height: 400px;
        max-height: 765px;
        border: 1px solid #ddd;
        background-color: #f9f9f9;
        overflow: auto;
        box-sizing: border-box;
    }
    /* 自定义甘特图任务颜色 */
    .gantt_task_complete {
        background-color: #4CAF50 !important;
        border-color: #388E3C !important;
    }
    .gantt_task_in_progress {
        background-color: #2196F3 !important;
        border-color: #1976D2 !important;
    }
    .gantt_task_overdue {
        background-color: #F44336 !important;
        border-color: #D32F2F !important;
    }
    .gantt_task_not_started {
        background-color: #9E9E9E !important;
        border-color: #757575 !important;
    }
    
    /* 时间刻度样式优化 */
    /* 主刻度样式 - 月 */
    .gantt_container .gantt_scale_line:first-child {
        background-color: #e3f2fd !important;
        font-weight: bold;
        color: #1565c0;
        border-bottom: 2px solid #1976d2;
        height: 35px !important;
        line-height: 35px !important;
    }
    
    /* 次刻度样式 - 天 */
    .gantt_container .gantt_scale_line:last-child {
        background-color: #f5f5f5 !important;
        font-weight: normal;
        color: #424242;
        border-bottom: 1px solid #e0e0e0;
        height: 25px !important;
        line-height: 25px !important;
    }
    
    /* 主刻度单元格样式 */
    .gantt_container .gantt_scale_line:first-child .gantt_scale_cell {
        border-right: 1px solid #bbdefb;
        text-align: center;
        font-size: 14px;
    }
    
    /* 次刻度单元格样式 */
    .gantt_container .gantt_scale_line:last-child .gantt_scale_cell {
        border-right: 1px solid #e0e0e0;
        text-align: center;
        font-size: 12px;
    }
    
    /* 周末日期特殊标记 */
    .gantt_container .gantt_scale_line:last-child .gantt_scale_cell:nth-child(7n),
    .gantt_container .gantt_scale_line:last-child .gantt_scale_cell:nth-child(7n-1) {
        background-color: #ffebee;
        color: #c62828;
    }
    /* 为所有标签页设置统一的最大高度和内部滚动 */
    .tab-content {
        min-height: 600px;
        max-height: 765px;
        overflow-y: auto;
    }
    
    /* 为members-tab特殊处理，移除滚动条限制 */
    #members-tab {
        max-height: none;
        overflow-y: visible;
    }
    
    /* 为gantt-tab特殊处理，移除滚动条限制 */
    #gantt-tab {
        max-height: none;
        overflow-y: visible;
    }
    /* 确保甘特图网格固定不滚动 */
    .gantt_container .gantt_grid {
        width: 730px !important;
        min-width: 730px !important;
        max-width: 730px !important;
        overflow-x: hidden !important;
        overflow-y: auto !important;
    }
    /* 确保甘特图时间线可以滚动 */
    .gantt_container .gantt_timeline {
        width: auto !important;
        min-width: 600px;
        overflow-x: auto !important;
        overflow-y: auto !important;
    }
    /* 隐藏网格区域的水平滚动条 */
    .gantt_container .gantt_grid .gantt_hor_scroll {
        display: none !important;
        height: 0 !important;
    }
    .gantt_container .gantt_grid .gantt_ver_scroll {
        display: block !important;
        width: 15px !important;
    }
    /* 确保时间线区域显示水平滚动条 */
    .gantt_container .gantt_timeline .gantt_hor_scroll {
        display: block !important;
        height: 15px !important;
    }
    .gantt_container .gantt_timeline .gantt_ver_scroll {
        display: block !important;
        width: 15px !important;
    }
    /* 隐藏网格区域的所有滚动条相关元素 */
    .gantt_container .gantt_grid_scale {
        overflow: hidden !important;
    }
    .gantt_container .gantt_task_cell {
        overflow: hidden !important;
    }
    .gantt_container .gantt_task_bg {
        overflow: hidden !important;
    }
    .gantt_container .gantt_grid_data {
        overflow: hidden !important;
    }
    
    /* 甘特图容器高度设置 */
    .gantt_container {
        min-height: 500px !important;
        max-height: 800px !important;
        overflow-y: auto !important;
    }
    /* 自定义下拉搜索框样式 */
    .custom-select-container {
        position: relative;
    }
    .custom-select-container input[type="text"] {
        cursor: pointer;
    }
    .custom-select-container .member-option {
        border-bottom: 1px solid #f0f0f0;
    }
    .custom-select-container .member-option:last-child {
        border-bottom: none;
    }
    .custom-select-container .member-option:hover {
        background-color: #f3f4f6;
    }
    .custom-select-container .member-option.selected {
        background-color: #e5e7eb;
    }
    .custom-select-container .no-results-option {
        cursor: default;
    }
    .custom-select-container .no-results-option:hover {
        background-color: transparent;
    }
    
    /* 确保添加任务按钮可点击 */
    #add-task-btn {
        cursor: pointer !important;
        pointer-events: auto !important;
        z-index: 10 !important;
        position: relative !important;
    }
    
    /* 确保模态框在顶层显示 */
    #add-task-modal {
        z-index: 9999 !important;
    }
</style>
{% endblock extra_css %}

{% block extra_js %}
{{ super() }}
<script src="https://cdn.dhtmlx.com/gantt/edge/dhtmlxgantt.js"></script>
<script src="{{ url_for('static', filename='js/memberManagement.js') }}"></script>
<script>
    // 获取CSRF令牌
    function getCsrfToken() {
        // 从meta标签中获取CSRF令牌
        const token = document.querySelector('meta[name="csrf-token"]');
        return token ? token.getAttribute('content') : '';
    }
    
    // 全局Toast提示函数（已删除Toast元素）
    function showToast(message, type = 'success') {
        // Toast元素已删除，改为控制台输出
        console.log('Toast[' + type + ']: ' + message);
    }
    
    // 隐藏Toast提示（已删除Toast元素）
    function hideToast(toastId) {
        // Toast元素已删除，此函数保留为空以保持兼容性
        console.log('hideToast: Toast元素已删除');
    }
    
    // 隐藏所有Toast提示（已删除Toast元素）
    function hideAllToasts() {
        // Toast元素已删除，此函数保留为空以保持兼容性
        console.log('hideAllToasts: Toast元素已删除');
    }
    
    // 初始化甘特图
    function initGantt() {
        // 捕获并忽略浏览器扩展相关的错误
        const originalConsoleError = console.error;
        console.error = function(...args) {
            // 忽略来自浏览器扩展的错误
            if (typeof args[0] === 'string' && 
                (args[0].includes('content.js') || 
                 args[0].includes('runtime.lastError') ||
                 args[0].includes('remove listener'))) {
                return; // 忽略这些错误
            }
            // 其他错误正常输出
            originalConsoleError.apply(console, args);
        };
        
        console.log("初始化甘特图...");
        
        // 检查gantt对象是否可用
        if (typeof gantt === 'undefined') {
            console.error("gantt对象未定义，请确保dhtmlxgantt.js已正确加载");
            // 恢复原始console.error函数
            console.error = originalConsoleError;
            return;
        }
        
        try {
            // 设置日期格式 - 使用dhtmlxGantt的标准格式
            gantt.config.date_format = "%Y-%m-%d";
            
            // 添加中文本地化配置
            gantt.locale = {
                date: {
                    month_full: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
                    month_short: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
                    day_full: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
                    day_short: ["日", "一", "二", "三", "四", "五", "六"]
                },
                labels: {
                    new_task: "新任务",
                    icon_save: "保存",
                    icon_cancel: "取消",
                    icon_delete: "删除",
                    icon_details: "详情",
                    icon_edit: "编辑",
                    icon_add: "添加",
                    wdg_confirm: "确认",
                    wdg_cancel: "取消",
                    wdg_apply: "应用",
                    wdg_today: "今天",
                    wdg_tomorrow: "明天",
                    wdg_yesterday: "昨天",
                    wdg_hour: "小时",
                    wdg_minute: "分钟",
                    wdg_year: "年",
                    wdg_month: "月",
                    wdg_day: "日",
                    wdg_week: "周",
                    wdg_time: "时间",
                    wdg_period: "周期",
                    wdg_repeats: "重复",
                    wdg_every: "每个",
                    wdg_first: "第一个",
                    wdg_second: "第二个",
                    wdg_third: "第三个",
                    wdg_fourth: "第四个",
                    wdg_last: "最后一个",
                    wdg_workday: "工作日",
                    wdg_weekend: "周末",
                    wdg_start: "开始",
                    wdg_end: "结束",
                    wdg_after: "之后",
                    wdg_before: "之前",
                    wdg_on: "在",
                    wdg_the: "的",
                    wdg_repeat: "重复",
                    wdg_repeat_every: "重复每个",
                    wdg_repeat_on: "重复在",
                    wdg_repeat_end: "重复结束",
                    wdg_repeat_never: "从不",
                    wdg_repeat_on_date: "在日期",
                    wdg_repeat_after: "之后",
                    wdg_repeat_occurrences: "次",
                    wdg_daily: "每天",
                    wdg_weekly: "每周",
                    wdg_monthly: "每月",
                    wdg_yearly: "每年",
                    wdg_custom: "自定义",
                    wdg_close: "关闭",
                    wdg_ok: "确定",
                    wdg_delete: "删除",
                    wdg_save: "保存",
                    wdg_loading: "加载中...",
                    wdg_connection_error: "连接错误",
                    wdg_invalid_url: "无效的URL",
                    wdg_no_data: "没有数据",
                    wdg_confirm_deletion: "确认删除",
                    wdg_confirm_saving: "确认保存",
                    wdg_confirm_cancellation: "确认取消",
                    wdg_section_description: "描述",
                    wdg_section_time: "时间",
                    wdg_section_period: "周期",
                    wdg_columns_text: "任务名称",
                    wdg_columns_start_date: "开始日期",
                    wdg_columns_duration: "持续时间",
                    wdg_columns_add: "添加",
                    wdg_columns_priority: "优先级",
                    wdg_columns_type: "类型",
                    wdg_columns_owner: "负责人",
                    wdg_columns_options: "选项",
                    wdg_columns_progress: "进度",
                    wdg_columns_status: "状态",
                    wdg_gantt_chart: "甘特图",
                    wdg_grid_header: "任务列表",
                    wdg_timeline_header: "时间轴",
                    wdg_task_progress: "任务进度",
                    wdg_task_status: "任务状态",
                    wdg_task_owner: "任务负责人",
                    wdg_task_start: "任务开始",
                    wdg_task_end: "任务结束",
                    wdg_task_duration: "任务持续时间",
                    wdg_task_type: "任务类型",
                    wdg_task_priority: "任务优先级",
                    wdg_task_description: "任务描述",
                    wdg_task_options: "任务选项",
                    wdg_task_add: "添加任务",
                    wdg_task_edit: "编辑任务",
                    wdg_task_delete: "删除任务",
                    wdg_task_save: "保存任务",
                    wdg_task_cancel: "取消任务",
                    wdg_task_details: "任务详情",
                    wdg_task_progress_text: "进度",
                    wdg_task_status_text: "状态",
                    wdg_task_owner_text: "负责人",
                    wdg_task_start_text: "开始",
                    wdg_task_end_text: "结束",
                    wdg_task_duration_text: "持续时间",
                    wdg_task_type_text: "类型",
                    wdg_task_priority_text: "优先级",
                    wdg_task_description_text: "描述",
                    wdg_task_options_text: "选项",
                    wdg_task_add_text: "添加",
                    wdg_task_edit_text: "编辑",
                    wdg_task_delete_text: "删除",
                    wdg_task_save_text: "保存",
                    wdg_task_cancel_text: "取消",
                    wdg_task_details_text: "详情",
                    wdg_confirm_delete: "确定要删除这个任务吗？",
                    wdg_confirm_save: "确定要保存这个任务吗？",
                    wdg_confirm_cancel: "确定要取消编辑这个任务吗？",
                    wdg_loading_data: "正在加载数据...",
                    wdg_no_tasks: "没有任务",
                    wdg_task_added: "任务已添加",
                    wdg_task_updated: "任务已更新",
                    wdg_task_deleted: "任务已删除",
                    wdg_error_occurred: "发生错误",
                    wdg_invalid_data: "无效的数据",
                    wdg_required_field: "必填字段",
                    wdg_invalid_date: "无效的日期",
                    wdg_invalid_duration: "无效的持续时间",
                    wdg_invalid_priority: "无效的优先级",
                    wdg_invalid_status: "无效的状态",
                    wdg_invalid_type: "无效的类型",
                    wdg_invalid_owner: "无效的负责人",
                    wdg_invalid_description: "无效的描述",
                    wdg_invalid_options: "无效的选项",
                    wdg_field_required: "此字段是必填的",
                    wdg_field_invalid: "此字段无效",
                    wdg_field_date: "请输入有效的日期",
                    wdg_field_duration: "请输入有效的持续时间",
                    wdg_field_priority: "请输入有效的优先级",
                    wdg_field_status: "请输入有效的状态",
                    wdg_field_type: "请输入有效的类型",
                    wdg_field_owner: "请输入有效的负责人",
                    wdg_field_description: "请输入有效的描述",
                    wdg_field_options: "请输入有效的选项"
                }
            };
            
            // 设置中文本地化
            gantt.i18n.setLocale("cn");
            
            // 配置日期显示格式（使用新版scale配置）
            gantt.config.scales = [
                {unit: "month", step: 1, format: "%Y年%m月"},
                {unit: "day", step: 1, format: "%d"}
            ];
            
            // 设置日期格式
            gantt.config.date_format = "%Y-%m-%d";
            gantt.config.xml_date = "%Y-%m-%d";
            
            // 添加缺失的重要配置项
            gantt.config.scale_height = 60;  // 增加时间刻度高度以适应新的样式
            gantt.config.task_height = 30;
            gantt.config.row_height = 40;
            gantt.config.add_column = false;
            gantt.config.autosize = "y";
            gantt.config.details_on_create = true;
            gantt.config.details_on_dblclick = true;
            gantt.config.correct_work_time = false;
            gantt.config.round_dnd_dates = false;
            
            // 设置时间轴单元格的最小宽度
            gantt.config.min_column_width = 30;
            
            // 添加明确的列配置
            gantt.config.columns = [
                {name: "text", label: "任务名称", width: 300, tree: true, template: function(obj) {
                    return obj.name || obj.text || "未命名任务";
                }},
                {name: "start_date", label: "开始日期", width: 150, align: "center", template: function(obj) {
                    if (obj.start_date) {
                        const date = gantt.date.parseDate(obj.start_date, gantt.config.date_format);
                        return gantt.date.date_to_str("%Y-%m-%d")(date);
                    }
                    return "";
                }},
                {name: "end_date", label: "结束日期", width: 150, align: "center", template: function(obj) {
                    if (obj.end_date) {
                        const date = gantt.date.parseDate(obj.end_date, gantt.config.date_format);
                        return gantt.date.date_to_str("%Y-%m-%d")(date);
                    }
                    return "";
                }},
                {name: "duration", label: "持续时间", width: 80, align: "center"},
                {name: "add", label: "", width: 40}
            ];
            
            // 配置甘特图布局
            gantt.config.layout = {
                css: "gantt_container",
                cols: [
                    {
                        width: 730,
                        min_width: 730,
                        rows: [
                            {view: "grid", scrollX: "gridScroll", scrollY: "scrollVer"},
                            {view: "scrollbar", id: "gridScroll", group: "horizontal"}
                        ]
                    },
                    {resizer: true, width: 1},
                    {
                        rows: [
                            {view: "timeline", scrollX: "scrollHor", scrollY: "scrollVer"},
                            {view: "scrollbar", id: "scrollHor", group: "horizontal"}
                        ]
                    },
                    {view: "scrollbar", id: "scrollVer", group: "vertical"}
                ]
            };
            
            // 配置滚动条
            gantt.config.show_links = true;
            gantt.config.show_grid = true;
            gantt.config.show_chart = true;
            
            // 确保网格区域不水平滚动
            gantt.config.grid_resize = false;
            
            // 隐藏网格区域的水平滚动条
            gantt.attachEvent("onGanttReady", function() {
                // 隐藏网格区域的水平滚动条
                var gridHorScroll = document.querySelector('.gantt_grid .gantt_hor_scroll');
                if (gridHorScroll) {
                    gridHorScroll.style.display = 'none';
                }
                
                // 确保时间线区域显示水平滚动条
                var timelineHorScroll = document.querySelector('.gantt_timeline .gantt_hor_scroll');
                if (timelineHorScroll) {
                    timelineHorScroll.style.display = 'block';
                }
            });
            
            // 自定义任务工具提示
            gantt.templates.tooltip_text = function(start, end, task) {
                return "<b>任务:</b> " + (task.name || task.text || "未命名任务") + 
                       "<br/><b>负责人:</b> " + (task.assignee || "未分配") +
                       "<br/><b>状态:</b> " + (task.status || "未设置") +
                       "<br/><b>进度:</b> " + Math.round((task.progress || 0) * 100) + "%";
            };
            
            // 自定义任务颜色
            gantt.templates.task_class = function(start, end, task) {
                if (task.status === "已完成") {
                    return "gantt_task_complete";
                } else if (task.status === "进行中") {
                    return "gantt_task_in_progress";
                } else if (task.status === "已延期") {
                    return "gantt_task_overdue";
                } else {
                    return "gantt_task_not_started";
                }
            };
            
            // 添加任务展开/收起事件监听
            gantt.attachEvent("onTaskOpen", function(id) {
                console.log("任务展开:", id);
                // 延迟保存状态, 确保甘特图已更新
                setTimeout(saveTaskOpenState, 100);
                return true;
            });
            
            gantt.attachEvent("onTaskClose", function(id) {
                console.log("任务收起:", id);
                // 延迟保存状态, 确保甘特图已更新
                setTimeout(saveTaskOpenState, 100);
                return true;
            });
            
            // 添加任务添加事件监听 - 当用户在甘特图中添加新任务时触发
            gantt.attachEvent("onAfterTaskAdd", function(id, task) {
                console.log("甘特图中添加了新任务:", id, task);
                
                // 获取项目ID
                var projectId = {{ project.id }};
                
                // 准备要发送到后端的数据
                var taskData = {
                    name: task.name || task.text || "新任务",
                    description: task.description || "",
                    start_date: task.start_date ? gantt.date.date_to_str("%Y-%m-%d")(new Date(task.start_date)) : "",
                    end_date: task.end_date ? gantt.date.date_to_str("%Y-%m-%d")(new Date(task.end_date)) : "",
                    progress: task.progress || 0,
                    status: task.status || "未开始",
                    assignee_id: task.assignee_id || null,
                    parent_id: task.parent || null
                };
                
                console.log("发送到后端的任务数据:", taskData);
                
                // 发送POST请求到后端API保存新任务
                fetch("/api/projects/" + projectId + "/tasks", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        "X-CSRFToken": getCsrfToken()
                    },
                    body: JSON.stringify(taskData)
                })
                .then(response => {
                    console.log("API响应状态:", response.status);
                    if (!response.ok) {
                        return response.json().then(err => {
                            throw new Error(err.message || 'Network response was not ok: ' + response.status);
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("任务保存成功:", data);
                    // 更新甘特图中的任务ID为后端返回的ID
                    if (data.success && data.task && data.task.id && data.task.id !== id) {
                        gantt.changeTaskId(id, data.task.id);
                        // 更新任务数据，确保name和text字段都存在
                        var updatedTask = gantt.getTask(data.task.id);
                        if (updatedTask) {
                            updatedTask.name = data.task.name;
                            updatedTask.text = data.task.name; // 确保text字段与name字段一致
                            gantt.updateTask(data.task.id);
                        }
                    }
                    // 重新加载甘特图数据以确保同步
                    loadProjectGantt();
                })
                .catch(error => {
                    console.error("保存任务失败:", error);
                    // 如果保存失败，从甘特图中移除该任务
                    gantt.deleteTask(id);
                    showFlashMessage("保存任务失败: " + error.message, "error");
                });
                
                return true;
            });
            
            // 添加任务更新事件监听 - 当用户在甘特图中更新任务时触发
            gantt.attachEvent("onAfterTaskUpdate", function(id, task) {
                console.log("甘特图中更新了任务:", id, task);
                
                // 准备要发送到后端的数据
                var taskData = {
                    name: task.name || task.text || "新任务",
                    description: task.description || "",
                    start_date: task.start_date ? gantt.date.date_to_str("%Y-%m-%d")(new Date(task.start_date)) : "",
                    end_date: task.end_date ? gantt.date.date_to_str("%Y-%m-%d")(new Date(task.end_date)) : "",
                    progress: task.progress || 0,
                    status: task.status || "未开始",
                    assignee_id: task.assignee_id || null,
                    parent_id: task.parent || null
                };
                
                console.log("发送到后端的更新任务数据:", taskData);
                
                // 发送PUT请求到后端API更新任务
                fetch("/api/task/" + id, {
                    method: "PUT",
                    headers: {
                        "Content-Type": "application/json",
                        "X-CSRFToken": getCsrfToken()
                    },
                    body: JSON.stringify(taskData)
                })
                .then(response => {
                    console.log("API响应状态:", response.status);
                    if (!response.ok) {
                        return response.json().then(err => {
                            throw new Error(err.message || 'Network response was not ok: ' + response.status);
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("任务更新成功:", data);
                    // 更新任务数据，确保name和text字段都存在
                    if (data.success && data.task) {
                        var updatedTask = gantt.getTask(id);
                        if (updatedTask) {
                            updatedTask.name = data.task.name;
                            updatedTask.text = data.task.name; // 确保text字段与name字段一致
                            gantt.updateTask(id);
                        }
                    }
                    // 重新加载甘特图数据以确保同步
                    loadProjectGantt();
                })
                .catch(error => {
                    console.error("更新任务失败:", error);
                    showFlashMessage("更新任务失败: " + error.message, "error");
                });
                
                return true;
            });
            
            // 添加任务删除事件监听 - 当用户在甘特图中删除任务时触发
            gantt.attachEvent("onAfterTaskDelete", function(id, task) {
                console.log("甘特图中删除了任务:", id, task);
                
                // 发送DELETE请求到后端API删除任务
                fetch("/api/task/" + id, {
                    method: "DELETE",
                    headers: {
                        "Content-Type": "application/json",
                        "X-CSRFToken": getCsrfToken()
                    }
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("任务删除成功:", data);
                    // 重新加载甘特图数据以确保同步
                    loadProjectGantt();
                })
                .catch(error => {
                    console.error("删除任务失败:", error);
                    showFlashMessage("删除任务失败，请重试", "error");
                });
                
                return true;
            });
            
            // 获取CSRF令牌的函数
            function getCsrfToken() {
                var csrfToken = document.querySelector('meta[name="csrf-token"]');
                if (csrfToken) {
                    return csrfToken.getAttribute('content');
                }
                
                // 如果meta标签中没有，尝试从cookie中获取
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = cookies[i].trim();
                    if (cookie.indexOf('csrf_token=') === 0) {
                        return cookie.substring('csrf_token='.length);
                    }
                }
                
                // 如果都没有，返回空字符串
                return "";
            }
            
            // 初始化甘特图
            var container = document.getElementById("gantt_here");
            if (!container) {
                console.error("甘特图容器不存在");
                return;
            }
            
            console.log("甘特图容器尺寸:", container.offsetWidth, "x", container.offsetHeight);
            
            // 确保容器有足够的尺寸
            if (container.offsetWidth < 100 || container.offsetHeight < 100) {
                console.warn("甘特图容器尺寸过小，尝试调整尺寸");
                container.style.width = "100%";
                container.style.height = "765px";
                console.log("调整后甘特图容器尺寸:", container.offsetWidth, "x", container.offsetHeight);
            }
            
            // 初始化甘特图
            gantt.init("gantt_here");
            console.log("甘特图初始化完成");
            
            // 添加窗口大小变化时的自适应处理
            window.addEventListener('resize', function() {
                // 延迟执行以确保DOM更新完成
                setTimeout(function() {
                    gantt.render();
                    
                    // 调整甘特图容器大小以适应内容
                    const container = document.getElementById("gantt_here");
                    if (container) {
                        // 获取甘特图实际需要的宽度
                        const gridWidth = document.querySelector('.gantt_grid')?.offsetWidth || 730;
                        const timelineWidth = document.querySelector('.gantt_timeline')?.offsetWidth || 600;
                        const totalWidth = gridWidth + timelineWidth + 1; // +1 for resizer
                        
                        // 如果容器宽度不足以显示所有内容，增加容器宽度
                        if (container.offsetWidth < totalWidth) {
                            container.style.width = totalWidth + 'px';
                            console.log("窗口大小变化，调整甘特图容器宽度为:", totalWidth + 'px');
                        }
                        
                        // 重新渲染甘特图以应用新尺寸
                        gantt.render();
                    }
                }, 100);
            });
        } catch (e) {
            console.error("甘特图配置失败:", e);
            var container = document.getElementById("gantt_here");
            if (container) {
                container.innerHTML = '<div class="text-center py-12"><p class="text-red-500">甘特图配置失败: ' + e.message + '</p></div>';
            }
        } finally {
            // 恢复原始console.error函数
            console.error = originalConsoleError;
        }
    }
    
    // 加载项目数据
    function loadProjectGantt() {
        var projectId = {{ project.id }};
        console.log("加载项目甘特图数据，项目ID:", projectId);
        
        // 获取项目数据
        fetch("/gantt/data/" + projectId)
            .then(response => {
                console.log("API响应状态:", response.status);
                if (!response.ok) {
                    throw new Error('Network response was not ok: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                console.log("API返回数据:", data);
                
                // 检查gantt对象是否可用
                if (typeof gantt === 'undefined') {
                    console.error("gantt对象未定义，无法加载数据");
                    return;
                }
                
                try {
                    // 清空甘特图
                    gantt.clearAll();
                    
                    // 检查数据结构
                    if (!data.data || !Array.isArray(data.data)) {
                        throw new Error("返回的数据结构不正确，缺少data数组");
                    }
                    
                    // 确保每个任务都有name和text字段
                    data.data.forEach(function(task) {
                        // 确保name字段存在
                        if (!task.name) {
                            task.name = task.text || "未命名任务";
                        }
                        // 确保text字段存在且与name字段一致
                        if (!task.text) {
                            task.text = task.name;
                        } else if (task.text !== task.name) {
                            task.text = task.name; // 确保text字段与name字段一致
                        }
                        console.log("任务数据:", task.id, task.name, task.text);
                    });
                    
                    // 直接使用API返回的数据，不进行额外处理
                    // 因为API已经返回了正确格式的数据
                    gantt.parse({
                        data: data.data,
                        links: data.links || []
                    });
                    
                    console.log("甘特图数据加载完成");
                    
                    // 恢复任务展开状态
                    restoreTaskOpenState();
                    
                    // 调整视图以显示所有任务
                    if (data.data.length > 0) {
                        // 显示第一个任务的开始日期
                        var firstTask = data.data[0];
                        if (firstTask.start_date) {
                            var startDate = new Date(firstTask.start_date);
                            gantt.showDate(startDate);
                            console.log("显示第一个任务的开始日期:", startDate);
                        }
                        
                        // 使用showDate和adjustViewport方法确保甘特图正确显示所有任务
                        setTimeout(() => {
                            // 替代fitToContent方法，使用可用的方法调整视图
                            if (gantt.showTask && data.data && data.data.length > 0) {
                                // 显示第一个任务
                                gantt.showTask(data.data[0].id);
                            }
                            // 调整视图以显示所有任务
                            if (gantt.adjustViewport) {
                                gantt.adjustViewport();
                            }
                            console.log("调用adjustViewport方法替代fitToContent");
                            
                            // 调整甘特图容器大小以适应内容
                            const container = document.getElementById("gantt_here");
                            if (container) {
                                // 获取甘特图实际需要的宽度，先检查元素是否存在
                                const gridElement = document.querySelector('.gantt_grid');
                                const timelineElement = document.querySelector('.gantt_timeline');
                                
                                if (gridElement && timelineElement) {
                                    const gridWidth = gridElement.offsetWidth;
                                    const timelineWidth = timelineElement.offsetWidth;
                                    const totalWidth = gridWidth + timelineWidth + 1; // +1 for resizer
                                    
                                    // 如果容器宽度不足以显示所有内容，增加容器宽度
                                    if (container.offsetWidth < totalWidth) {
                                        container.style.width = totalWidth + 'px';
                                        console.log("调整甘特图容器宽度为:", totalWidth + 'px');
                                    }
                                    
                                    // 重新初始化甘特图以应用新尺寸
                                    gantt.render();
                                } else {
                                    console.log("甘特图网格或时间线元素尚未渲染，跳过宽度调整");
                                }
                            }
                        }, 300);
                        
                        // 确保甘特图容器可以滚动
                        setTimeout(function() {
                            // 重新渲染甘特图以确保滚动条正确显示
                            gantt.render();
                            
                            // 确保网格区域的水平滚动条被隐藏
                            var gridHorScroll = document.querySelector('.gantt_grid .gantt_hor_scroll');
                            if (gridHorScroll) {
                                gridHorScroll.style.display = 'none';
                                gridHorScroll.style.height = '0';
                            }
                            
                            // 确保时间线区域显示水平滚动条
                            var timelineHorScroll = document.querySelector('.gantt_timeline .gantt_hor_scroll');
                            if (timelineHorScroll) {
                                timelineHorScroll.style.display = 'block';
                                timelineHorScroll.style.height = '15px';
                            }
                            
                            // 确保垂直滚动条正确显示
                            var verScroll = document.querySelector('.gantt_container .gantt_ver_scroll');
                            if (verScroll) {
                                verScroll.style.display = 'block';
                                verScroll.style.width = '15px';
                            }
                        }, 500);
                    } else {
                        console.log("项目没有任务数据");
                    }
                } catch (e) {
                    console.error("处理甘特图数据失败:", e);
                }
            })
            .catch(error => {
                console.error('Error loading project data:', error);
            });
    }
    
    // 保存任务展开状态
    function saveTaskOpenState() {
        if (typeof gantt === 'undefined') {
            return;
        }
        
        const projectId = {{ project.id }};
        const state = {};
        
        // 遍历所有任务, 记录展开状态
        gantt.eachTask(function(task) {
            state[task.id] = !!task.$open; // 转换为布尔值
        });
        
        // 保存到localStorage
        localStorage.setItem(`gantt_open_state_${projectId}`, JSON.stringify(state));
        console.log("已保存任务展开状态", state);
    }
    
    // 恢复任务展开状态
    function restoreTaskOpenState() {
        if (typeof gantt === 'undefined') {
            return;
        }
        
        const projectId = {{ project.id }};
        const savedState = localStorage.getItem(`gantt_open_state_${projectId}`);
        
        if (!savedState) {
            console.log("没有找到保存的任务展开状态");
            return;
        }
        
        try {
            const state = JSON.parse(savedState);
            console.log("恢复任务展开状态", state);
            
            // 应用保存的状态
            gantt.eachTask(function(task) {
                if (state.hasOwnProperty(task.id)) {
                    // 如果有子任务, 才设置展开状态
                    if (gantt.hasChild(task.id)) {
                        if (state[task.id]) {
                            gantt.open(task.id);
                        } else {
                            gantt.close(task.id);
                        }
                    }
                }
            });
        } catch (e) {
            console.error("恢复任务展开状态失败:", e);
        }
    }
    
    // 添加成员相关代码已移至members_list.html
    
    // 标签页切换功能 - 简化版本
    function initTabSwitching() {
        console.log('初始化标签页切换功能');
        
        // 获取所有标签按钮和内容
        const tabButtons = document.querySelectorAll('.tab-button');
        const tabContents = document.querySelectorAll('.tab-content');
        
        console.log('找到的标签按钮数量:', tabButtons.length);
        console.log('找到的标签内容数量:', tabContents.length);
        
        // 检查是否找到了标签按钮和内容
        if (tabButtons.length === 0) {
            console.error('未找到任何标签按钮');
            return;
        }
        
        if (tabContents.length === 0) {
            console.error('未找到任何标签内容');
            return;
        }
        
        // 为每个标签按钮添加点击事件
        tabButtons.forEach(button => {
            console.log('为按钮添加点击事件:', button.getAttribute('data-tab'));
            
            // 移除之前可能存在的事件监听器
            button.removeEventListener('click', handleTabClick);
            
            // 添加新的事件监听器
            button.addEventListener('click', handleTabClick);
        });
        
        // 检查URL参数，激活对应的标签页
        const urlParams = new URLSearchParams(window.location.search);
        const activeTab = urlParams.get('active_tab');
        if (activeTab) {
            console.log('URL参数中指定了激活的标签页:', activeTab);
            const targetButton = document.querySelector(`.tab-button[data-tab="${activeTab}"]`);
            if (targetButton) {
                console.log('找到目标按钮，触发点击事件');
                switchTab(targetButton.getAttribute('data-tab'));
            } else {
                console.error('未找到URL参数指定的标签按钮:', activeTab);
            }
        }
        
        console.log('标签页切换功能初始化完成');
    }
    
    // 处理标签点击事件的函数
    function handleTabClick(event) {
        event.preventDefault();
        event.stopPropagation();
        
        const targetTab = this.getAttribute('data-tab');
        console.log('点击了标签按钮:', targetTab);
        
        switchTab(targetTab);
    }
    
    // 切换标签的函数
    function switchTab(targetTab) {
        console.log('切换到标签:', targetTab);
        
        // 获取所有标签按钮和内容
        const tabButtons = document.querySelectorAll('.tab-button');
        const tabContents = document.querySelectorAll('.tab-content');
        
        // 移除所有标签按钮的激活状态
        tabButtons.forEach(btn => {
            btn.classList.remove('border-primary', 'text-primary');
            btn.classList.add('border-transparent', 'text-gray-500');
        });
        
        // 激活当前点击的标签按钮
        const activeButton = document.querySelector(`.tab-button[data-tab="${targetTab}"]`);
        if (activeButton) {
            activeButton.classList.remove('border-transparent', 'text-gray-500');
            activeButton.classList.add('border-primary', 'text-primary');
        }
        
        // 隐藏所有标签内容
        tabContents.forEach(content => {
            content.classList.add('hidden');
        });
        
        // 显示当前点击的标签内容
        const targetContent = document.getElementById(targetTab + '-tab');
        console.log('目标内容元素:', targetContent);
        if (targetContent) {
            targetContent.classList.remove('hidden');
            console.log('已显示标签内容:', targetTab + '-tab');
            
            // 如果切换到任务列表标签页，重新初始化添加任务按钮事件
            if (targetTab === 'tasks') {
                console.log('重新初始化添加任务按钮事件');
                setTimeout(() => {
                    initAddTaskButton();
                }, 100);
            }
            
            // 如果切换到甘特图标签，初始化甘特图
            if (targetTab === 'gantt') {
                console.log('初始化甘特图');
                setTimeout(() => {
                    if (typeof initGantt === 'function') {
                        initGantt();
                        // 初始化完成后加载数据
                        setTimeout(() => {
                            if (typeof loadProjectGantt === 'function') {
                                loadProjectGantt();
                            } else {
                                console.error('loadProjectGantt 函数未定义');
                            }
                        }, 200);
                    } else {
                        console.error('initGantt 函数未定义');
                    }
                }, 100);
            }
            
            // 如果切换到成员管理标签页，初始化成员管理模块
            if (targetTab === 'members') {
                console.log('初始化成员管理模块');
                setTimeout(() => {
                    // 初始化成员管理模块
                    if (typeof MemberManagement !== 'undefined') {
                        const projectId = {{ project.id }};
                        const containerId = 'members-tab';
                        console.log('初始化MemberManagement模块，项目ID:', projectId, '容器ID:', containerId);
                        
                        try {
                            MemberManagement.init(projectId, containerId);
                            console.log('MemberManagement模块初始化成功');
                        } catch (error) {
                            console.error('MemberManagement模块初始化失败:', error);
                        }
                    } else {
                        console.error('MemberManagement模块未定义');
                    }
                }, 100);
            }
            
            // 如果切换到周报标签页，加载周报数据
            if (targetTab === 'reports') {
                console.log('加载周报数据');
                setTimeout(() => {
                    loadWeeklyReports();
                }, 100);
            }
            
            // 如果切换到健康度标签页，加载健康度数据
            if (targetTab === 'health') {
                console.log('加载项目健康度数据');
                setTimeout(() => {
                    loadProjectHealth();
                }, 100);
            }
            
            // 如果切换到里程碑-任务层次结构标签页，不需要额外初始化
            if (targetTab === 'milestone-hierarchy') {
                console.log('显示里程碑-任务层次结构');
            }
        } else {
            console.error('未找到标签内容:', targetTab + '-tab');
        }
    }
    
    // 在DOM加载完成后初始化标签页切换功能
    document.addEventListener('DOMContentLoaded', function() {
        try {
            console.log('DOM内容已加载，开始初始化标签页切换功能');
            
            // 确保Toast元素初始状态为隐藏
            const successToast = document.getElementById('successToast');
            const errorToast = document.getElementById('errorToast');
            
            if (successToast && !successToast.classList.contains('-translate-x-full')) {
                successToast.classList.add('-translate-x-full');
                console.log('设置成功Toast为隐藏状态');
            }
            
            if (errorToast && !errorToast.classList.contains('-translate-x-full')) {
                errorToast.classList.add('-translate-x-full');
                console.log('设置错误Toast为隐藏状态');
            }
            
            initTabSwitching();
            
            // 延迟初始化添加任务按钮事件，确保DOM完全加载
            setTimeout(() => {
                initAddTaskButton();
            }, 300);
        } catch (error) {
            console.error('初始化标签页切换功能时发生错误:', error);
        }
    });
    
    // 初始化添加任务按钮事件
    function initAddTaskButton() {
        console.log('初始化添加任务按钮事件');
        
        // 获取添加任务按钮
        const addTaskBtn = document.getElementById('add-task-btn');
        if (!addTaskBtn) {
            console.error('未找到添加任务按钮');
            return;
        }
        
        // 移除之前可能存在的事件监听器
        addTaskBtn.removeEventListener('click', handleAddTaskClick);
        
        // 添加点击事件监听器
        addTaskBtn.addEventListener('click', handleAddTaskClick);
        
        // 获取关闭按钮
        const closeAddTaskModal = document.getElementById('close-add-task-modal');
        if (closeAddTaskModal) {
            // 移除之前可能存在的事件监听器
            closeAddTaskModal.removeEventListener('click', handleCloseAddTaskModal);
            
            // 添加点击事件监听器
            closeAddTaskModal.addEventListener('click', handleCloseAddTaskModal);
        }
        
        // 获取取消按钮
        const cancelAddTask = document.getElementById('cancel-add-task');
        if (cancelAddTask) {
            // 移除之前可能存在的事件监听器
            cancelAddTask.removeEventListener('click', handleCloseAddTaskModal);
            
            // 添加点击事件监听器
            cancelAddTask.addEventListener('click', handleCloseAddTaskModal);
        }
        
        // 获取添加任务表单
        const addTaskForm = document.getElementById('add-task-form');
        if (addTaskForm) {
            // 移除之前可能存在的事件监听器
            addTaskForm.removeEventListener('submit', handleAddTaskSubmit);
            
            // 添加提交事件监听器
            addTaskForm.addEventListener('submit', handleAddTaskSubmit);
        }
        
        console.log('添加任务按钮事件初始化完成');
    }
    
    // 处理添加任务按钮点击事件
    function handleAddTaskClick(event) {
        event.preventDefault();
        event.stopPropagation();
        
        console.log('点击了添加任务按钮');
        
        // 获取添加任务模态框
        const modal = document.getElementById('add-task-modal');
        if (modal) {
            // 显示模态框
            modal.classList.remove('hidden');
            console.log('显示添加任务模态框');
            
            // 重置表单
            const form = document.getElementById('add-task-form');
            if (form) {
                form.reset();
                console.log('重置添加任务表单');
            }
        } else {
            console.error('未找到添加任务模态框');
        }
    }
    
    // 处理关闭添加任务模态框事件
    function handleCloseAddTaskModal(event) {
        event.preventDefault();
        event.stopPropagation();
        
        console.log('关闭添加任务模态框');
        
        // 获取添加任务模态框
        const modal = document.getElementById('add-task-modal');
        if (modal) {
            // 隐藏模态框
            modal.classList.add('hidden');
            console.log('隐藏添加任务模态框');
        } else {
            console.error('未找到添加任务模态框');
        }
    }
    
    // 处理添加任务表单提交事件
    function handleAddTaskSubmit(event) {
        console.log('提交添加任务表单');
        
        // 表单提交前的验证
        const form = event.target;
        const taskName = document.getElementById('task-name').value.trim();
        
        if (!taskName) {
            event.preventDefault();
            showToast('请输入任务名称', 'error');
            return;
        }
        
        // 检查开始日期和结束日期的逻辑关系
        const startDate = document.getElementById('task-start-date').value;
        const endDate = document.getElementById('task-end-date').value;
        
        if (startDate && endDate && startDate > endDate) {
            event.preventDefault();
            showToast('开始日期不能晚于结束日期', 'error');
            return;
        }
        
        // 使用Ajax提交表单，避免页面刷新
        event.preventDefault();
        
        // 获取表单数据
        const formData = new FormData(form);
        
        // 发送Ajax请求
        fetch(form.action, {
            method: 'POST',
            body: formData,
            headers: {
                'X-CSRFToken': getCsrfToken()
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            console.log('任务创建成功:', data);
            
            // 关闭模态框
            const modal = document.getElementById('add-task-modal');
            if (modal) {
                modal.classList.add('hidden');
            }
            
            // 显示成功消息
            showToast('任务创建成功', 'success');
            
            // 刷新任务列表
            refreshTaskList();
        })
        .catch(error => {
            console.error('创建任务失败:', error);
            showToast('创建任务失败，请重试', 'error');
        });
    }
    
    // 刷新任务列表
    function refreshTaskList() {
        console.log('刷新任务列表');
        
        const projectId = document.getElementById('add-task-btn').getAttribute('data-project-id');
        if (!projectId) {
            console.error('未找到项目ID');
            return;
        }
        
        // 使用Ajax获取最新的任务列表
        fetch(`/api/projects/${projectId}/tasks`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.text();
        })
        .then(html => {
            // 更新任务列表容器
            const tasksContainer = document.getElementById('tasks-container');
            if (tasksContainer) {
                tasksContainer.innerHTML = html;
                
                // 重新绑定删除任务事件
                bindDeleteTaskEvents();
                
                console.log('任务列表刷新成功');
            } else {
                console.error('未找到任务列表容器');
            }
        })
        .catch(error => {
            console.error('刷新任务列表失败:', error);
            showToast('刷新任务列表失败，请刷新页面', 'error');
        });
    }
    
    // 绑定删除任务事件
    function bindDeleteTaskEvents() {
        console.log('绑定删除任务事件');
        
        // 获取所有删除任务按钮
        const deleteButtons = document.querySelectorAll('.delete-task');
        if (deleteButtons.length === 0) {
            console.log('未找到删除任务按钮');
            return;
        }
        
        // 为每个删除按钮添加点击事件
        deleteButtons.forEach(button => {
            // 移除之前可能存在的事件监听器
            button.removeEventListener('click', handleDeleteTaskClick);
            
            // 添加新的事件监听器
            button.addEventListener('click', handleDeleteTaskClick);
        });
        
        console.log('删除任务事件绑定完成');
    }
    
    // 处理删除任务按钮点击事件
    function handleDeleteTaskClick(event) {
        event.preventDefault();
        event.stopPropagation();
        
        const button = event.currentTarget;
        const taskId = button.getAttribute('data-task-id');
        const taskName = button.getAttribute('data-task-name');
        
        if (!taskId || !taskName) {
            console.error('未找到任务ID或任务名称');
            return;
        }
        
        // 设置删除确认模态框中的任务名称
        const deleteTaskName = document.getElementById('delete-task-name');
        if (deleteTaskName) {
            deleteTaskName.textContent = taskName;
        }
        
        // 设置删除确认模态框中的任务ID
        const deleteTaskId = document.getElementById('delete-task-id');
        if (deleteTaskId) {
            deleteTaskId.value = taskId;
        }
        
        // 显示删除确认模态框
        const deleteModal = document.getElementById('delete-task-modal');
        if (deleteModal) {
            deleteModal.classList.remove('hidden');
        }
    }
    
    // 在页面加载完成后再次尝试初始化（确保所有资源都已加载）
    window.addEventListener('load', function() {
        try {
            console.log('页面完全加载，重新初始化标签页切换功能');
            initTabSwitching();
            
            // 确保Toast元素初始状态为隐藏
            const successToast = document.getElementById('successToast');
            const errorToast = document.getElementById('errorToast');
            
            if (successToast && !successToast.classList.contains('-translate-x-full')) {
                successToast.classList.add('-translate-x-full');
            }
            
            if (errorToast && !errorToast.classList.contains('-translate-x-full')) {
                errorToast.classList.add('-translate-x-full');
            }
        } catch (error) {
            console.error('重新初始化标签页切换功能时发生错误:', error);
        }
    });
</script>
{% endblock extra_js %}



{% block content %}
<div class="container mx-auto space-y-6">
    <!-- 面包屑导航 -->
    <nav class="text-sm breadcrumbs mb-6">
        <ol class="flex items-center space-x-2">
            <li><a href="{{ url_for('main.home') }}" class="text-gray-500 hover:text-gray-700">首页</a></li>
            <li><i class="fas fa-chevron-right text-gray-400 text-xs mx-2"></i></li>
            <li><a href="{{ url_for('project.list_projects') }}" class="text-gray-500 hover:text-gray-700">项目管理</a></li>
            <li><i class="fas fa-chevron-right text-gray-400 text-xs mx-2"></i></li>
            <li class="text-gray-700">项目详情</li>
        </ol>
    </nav>

    <!-- 项目基本信息卡片 -->
    <div class="bg-white rounded-lg shadow mb-6">
        <div class="p-6">
            <div class="flex justify-between items-start">
                <div class="flex items-center">
                    <div class="flex-shrink-0 h-16 w-16">
                        <div class="h-16 w-16 rounded-full bg-blue-100 flex items-center justify-center">
                            <i class="fas fa-project-diagram text-blue-500 text-2xl"></i>
                        </div>
                    </div>
                    <div class="ml-4">
                        <h2 class="text-2xl font-bold text-gray-900">{{ project.name }}</h2>
                        <p class="text-sm text-gray-500">项目编号: {{ project.project_number or '无' }}</p>
                    </div>
                </div>
                <div class="flex space-x-2">
                    <a href="{{ url_for('project.edit_project', project_id=project.id) }}" class="px-4 py-2 bg-white border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 transition">
                        <i class="fas fa-edit mr-2"></i>编辑
                    </a>
                    <button class="delete-project px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 transition" data-id="{{ project.id }}" data-name="{{ project.name }}">
                        <i class="fas fa-trash mr-2"></i>删除
                    </button>
                </div>
            </div>

            <div class="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <h3 class="text-lg font-medium text-gray-900 mb-4">基本信息</h3>
                    <dl class="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-2">
                        <div>
                            <dt class="text-sm font-medium text-gray-500">项目类型</dt>
                            <dd class="mt-1 text-sm text-gray-900">{{ project.project_type or '产品研发' }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">项目来源</dt>
                            <dd class="mt-1 text-sm text-gray-900">{{ project.project_source or '公开招标' }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">项目规模</dt>
                            <dd class="mt-1 text-sm text-gray-900">{{ project.scale or '中型' }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">负责人</dt>
                            <dd class="mt-1 text-sm text-gray-900">{{ project.manager.name if project.manager else '未分配' }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">销售负责人</dt>
                            <dd class="mt-1 text-sm text-gray-900">{{ project.sales_manager.name if project.sales_manager else '未分配' }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">开始日期</dt>
                            <dd class="mt-1 text-sm text-gray-900">{{ project.start_date.strftime('%Y-%m-%d') if project.start_date else '未设置' }}</dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">结束日期</dt>
                            <dd class="mt-1 text-sm text-gray-900">{{ project.end_date.strftime('%Y-%m-%d') if project.end_date else '未设置' }}</dd>
                        </div>
                    </dl>
                </div>
                <div>
                    <h3 class="text-lg font-medium text-gray-900 mb-4">状态与进度</h3>
                    <dl class="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-2">
                        <div>
                            <dt class="text-sm font-medium text-gray-500">状态</dt>
                            <dd class="mt-1">
                                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full {% if project.status == '未开始' %}bg-gray-100 text-gray-800{% elif project.status == '进行中' %}bg-blue-100 text-blue-800{% elif project.status == '已完成' %}bg-green-100 text-green-800{% else %}bg-red-100 text-red-800{% endif %}">
                                    {{ project.status }}
                                </span>
                            </dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">进度</dt>
                            <dd class="mt-1">
                                <div class="w-full bg-gray-200 rounded-full h-2.5">
                                    <div class="h-2.5 rounded-full progress-bar" 
                                         data-progress="{{ project.progress }}"
                                         style="width: {{ project.progress }}%; background-color: {% if project.progress >= 100 %}#10B981{% elif project.progress >= 50 %}#3B82F6{% else %}#F59E0B{% endif %};">
                                    </div>
                                </div>
                                <span class="text-xs text-gray-500">{{ project.progress }}%</span>
                            </dd>
                        </div>
                        <div>
                            <dt class="text-sm font-medium text-gray-500">关联客户</dt>
                            <dd class="mt-1 text-sm text-gray-900">
                                {% if project.customer %}
                                    <a href="{{ url_for('customer.customer_detail', customer_id=project.customer.id) }}" class="text-primary hover:text-blue-600">
                                        {{ project.customer.name }}
                                    </a>
                                {% else %}
                                    <span class="text-gray-500">未关联客户</span>
                                {% endif %}
                            </dd>
                        </div>
                    </dl>
                </div>
            </div>

            <div class="mt-6">
                <h3 class="text-lg font-medium text-gray-900 mb-2">项目描述</h3>
                <p class="text-sm text-gray-700">{{ project.description if project.description else '暂无项目描述' }}</p>
            </div>
        </div>
    </div>

    <!-- 标签页导航 -->
    <div class="bg-white rounded-lg shadow mb-6">
        <div class="border-b border-gray-200">
            <nav class="-mb-px flex" aria-label="Tabs">
                <button class="tab-button border-b-2 border-primary text-primary font-medium py-4 px-6 text-sm focus:outline-none transition" data-tab="tasks">
                    <i class="fas fa-tasks mr-2"></i>任务列表
                </button>
                <button class="tab-button border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 font-medium py-4 px-6 text-sm focus:outline-none transition" data-tab="members">
                    <i class="fas fa-users mr-2"></i>成员管理
                </button>
                <button class="tab-button border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 font-medium py-4 px-6 text-sm focus:outline-none transition" data-tab="gantt">
                    <i class="fas fa-chart-gantt mr-2"></i>甘特图
                </button>
                <button class="tab-button border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 font-medium py-4 px-6 text-sm focus:outline-none transition" data-tab="milestones">
                    <i class="fas fa-flag mr-2"></i>里程碑管理
                </button>
                <button class="tab-button border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 font-medium py-4 px-6 text-sm focus:outline-none transition" data-tab="milestone-hierarchy">
                    <i class="fas fa-sitemap mr-2"></i>里程碑-任务层次
                </button>
                <button class="tab-button border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 font-medium py-4 px-6 text-sm focus:outline-none transition" data-tab="reports">
                    <i class="fas fa-file-alt mr-2"></i>周报中心
                </button>
                <button class="tab-button border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 font-medium py-4 px-6 text-sm focus:outline-none transition" data-tab="health">
                    <i class="fas fa-heartbeat mr-2"></i>项目健康度
                </button>
            </nav>
        </div>

        <!-- 任务列表标签页 -->
        <div id="tasks-tab" class="tab-content p-6">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-medium text-gray-900">项目任务</h3>
                <button id="add-task-btn" type="button" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-blue-600 transition relative z-10" data-project-id="{{ project.id }}" style="position: relative; z-index: 10;">
                    <i class="fas fa-plus mr-2"></i>添加任务
                </button>
            </div>
            <div id="tasks-container">
                {% include 'partials/tasks_list.html' with context %}
            </div>
        </div>

    <!-- 成员管理标签页 -->
    <div id="members-tab" class="tab-content p-6 hidden">
        <div id="members-container">
            {% include 'partials/members_list.html' with context %}
        </div>
    </div>

    <!-- 甘特图标签页 -->
    <div id="gantt-tab" class="tab-content p-6 hidden">
        <div class="mb-4">
            <h3 class="text-lg font-medium text-gray-900">项目甘特图</h3>
        </div>
        <div class="bg-white rounded-lg shadow overflow-hidden">
            <div id="gantt_here" class="gantt_container" style="overflow-x: hidden;"></div>
        </div>
    </div>

    <!-- 里程碑管理标签页 -->
    <div id="milestones-tab" class="tab-content p-6 hidden">
        <div class="bg-white rounded-lg shadow">
            <div class="px-6 py-4 border-b border-gray-200 flex justify-between items-center">
                <h3 class="text-lg font-medium text-gray-900">项目里程碑</h3>
                <button onclick="document.getElementById('create-milestone-modal').classList.remove('hidden')" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition">
                    <i class="fas fa-plus mr-2"></i>创建里程碑
                </button>
            </div>
            <div class="p-6">
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">里程碑名称</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">描述</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">截止日期</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200" id="milestones-tbody">
                            <!-- 里程碑数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                    <div id="milestones-loading" class="text-center py-4">
                        <i class="fas fa-spinner fa-spin text-gray-400"></i>
                        <span class="ml-2 text-gray-500">加载中...</span>
                    </div>
                    <div id="milestones-empty" class="text-center py-4 hidden">
                        <p class="text-gray-500">暂无里程碑</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 里程碑-任务层次结构标签页 -->
    <div id="milestone-hierarchy-tab" class="tab-content p-6 hidden">
        {% include 'partials/milestones_tasks_hierarchy.html' %}
    </div>

    <!-- 周报中心标签页 -->
    <div id="reports-tab" class="tab-content p-6 hidden">
        <div class="bg-white rounded-lg shadow">
            <div class="px-6 py-4 border-b border-gray-200 flex justify-between items-center">
                <h3 class="text-lg font-medium text-gray-900">项目周报</h3>
                <button onclick="document.getElementById('weeklyReportModal').classList.remove('hidden')" class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition">
                    <i class="fas fa-plus mr-2"></i>填报周报
                </button>
            </div>
            <div class="p-6">
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">周开始日期</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">周结束日期</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">填报人</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">工作时长</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">工作内容</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">下周计划</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">遇到问题</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200" id="reports-tbody">
                            <!-- 周报数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                    <div id="reports-loading" class="text-center py-4">
                        <i class="fas fa-spinner fa-spin text-gray-400"></i>
                        <span class="ml-2 text-gray-500">加载中...</span>
                    </div>
                    <div id="reports-empty" class="text-center py-4 hidden">
                        <p class="text-gray-500">暂无周报</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 项目健康度标签页 -->
    <div id="health-tab" class="tab-content p-6 hidden">
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- 项目健康度评分 -->
            <div class="bg-white rounded-lg shadow p-6">
                <h3 class="text-lg font-medium text-gray-900 mb-4">项目健康度评分</h3>
                <div class="flex flex-col items-center justify-center h-48">
                    <div class="relative">
                        <svg class="w-32 h-32">
                            <circle cx="64" cy="64" r="56" stroke="#e5e7eb" stroke-width="12" fill="none"></circle>
                            <circle id="health-circle" cx="64" cy="64" r="56" stroke="#10b981" stroke-width="12" fill="none"
                                    stroke-dasharray="351.86" stroke-dashoffset="88" stroke-linecap="round"
                                    transform="rotate(-90 64 64)"></circle>
                        </svg>
                        <div class="absolute inset-0 flex items-center justify-center">
                            <div class="text-center">
                                <div id="health-score" class="text-3xl font-bold text-gray-900">85</div>
                                <div id="health-status" class="text-sm text-gray-500">良好</div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="mt-6 space-y-3">
                    <div class="flex justify-between items-center">
                        <span class="text-sm text-gray-600">延期天数</span>
                        <span id="delay-days" class="text-sm font-medium text-gray-900">0天</span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-sm text-gray-600">任务完成率</span>
                        <span id="task-completion" class="text-sm font-medium text-gray-900">75%</span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-sm text-gray-600">里程碑完成率</span>
                        <span id="milestone-completion" class="text-sm font-medium text-gray-900">60%</span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-sm text-gray-600">成本使用率</span>
                        <span id="cost-usage" class="text-sm font-medium text-gray-900">80%</span>
                    </div>
                </div>
            </div>

            <!-- 项目健康度趋势 -->
            <div class="bg-white rounded-lg shadow p-6">
                <h3 class="text-lg font-medium text-gray-900 mb-4">健康度趋势</h3>
                <div id="health-trend-chart" class="h-64 w-full"></div>
            </div>
        </div>

        <!-- 项目风险提示 -->
        <div class="mt-6 bg-white rounded-lg shadow p-6">
            <h3 class="text-lg font-medium text-gray-900 mb-4">风险提示</h3>
            <div id="risk-alerts" class="space-y-3">
                <!-- 风险提示将通过JavaScript动态加载 -->
            </div>
            <div id="no-risks" class="text-center py-4 hidden">
                <p class="text-gray-500">暂无风险提示</p>
            </div>
        </div>
    </div>
        <!-- 添加成员模态框已移至members_list.html -->

        <!-- 编辑成员和删除成员的模态框已移至members_list.html -->

        <!-- 添加任务模态框 -->
        <div id="add-task-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden flex items-center justify-center" style="position: fixed; z-index: 1000;">
            <div class="relative p-5 border w-11/12 md:w-2/3 lg:w-2/5 xl:w-1/3 shadow-lg rounded-md bg-white max-h-[90vh] overflow-y-auto" style="position: relative; z-index: 1001;">
                <div class="mt-3">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-medium text-gray-900">添加任务</h3>
                        <button id="close-add-task-modal" class="text-gray-400 hover:text-gray-500">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    <form id="add-task-form" action="{{ url_for('task.task_create', project_id=project.id) }}" method="post">
                        <input type="hidden" name="project_id" value="{{ project.id }}">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <!-- 任务名称 -->
                            <div class="md:col-span-2">
                                <label for="task-name" class="block text-sm font-medium text-gray-700 mb-1">任务名称 <span class="text-red-500">*</span></label>
                                <input 
                                    type="text" 
                                    id="task-name" 
                                    name="name" 
                                    required
                                    class="block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm transition-all duration-300"
                                >
                            </div>
                            
                            <!-- 父任务 -->
                            <div>
                                <label for="task-parent" class="block text-sm font-medium text-gray-700 mb-1">父任务</label>
                                <select 
                                    id="task-parent" 
                                    name="parent_id" 
                                    class="block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm transition-all duration-300"
                                >
                                    <option value="0">无(顶级任务)</option>
                                    {% for task in project_tasks %}
                                    <option value="{{ task.id }}">{{ task.name }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            
                            <!-- 负责人 -->
                            <div>
                                <label for="task-assignee" class="block text-sm font-medium text-gray-700 mb-1">负责人</label>
                                <select 
                                    id="task-assignee" 
                                    name="assignee_id" 
                                    class="block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm transition-all duration-300"
                                >
                                    <option value="">请选择负责人</option>
                                    {% for member in project_members %}
                                    <option value="{{ member.id }}">{{ member.name }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            
                            <!-- 优先级 -->
                            <div>
                                <label for="task-priority" class="block text-sm font-medium text-gray-700 mb-1">优先级</label>
                                <select 
                                    id="task-priority" 
                                    name="priority" 
                                    class="block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm transition-all duration-300"
                                >
                                    <option value="低">低</option>
                                    <option value="中" selected>中</option>
                                    <option value="高">高</option>
                                    <option value="紧急">紧急</option>
                                </select>
                            </div>
                            
                            <!-- 状态 -->
                            <div>
                                <label for="task-status" class="block text-sm font-medium text-gray-700 mb-1">状态</label>
                                <select 
                                    id="task-status" 
                                    name="status" 
                                    class="block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm transition-all duration-300"
                                >
                                    <option value="未开始" selected>未开始</option>
                                    <option value="进行中">进行中</option>
                                    <option value="已完成">已完成</option>
                                    <option value="已暂停">已暂停</option>
                                </select>
                            </div>
                            
                            <!-- 开始日期 -->
                            <div>
                                <label for="task-start-date" class="block text-sm font-medium text-gray-700 mb-1">开始日期</label>
                                <input 
                                    type="date" 
                                    id="task-start-date" 
                                    name="start_date" 
                                    class="block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm transition-all duration-300"
                                >
                            </div>
                            
                            <!-- 截止日期 -->
                            <div>
                                <label for="task-end-date" class="block text-sm font-medium text-gray-700 mb-1">截止日期</label>
                                <input 
                                    type="date" 
                                    id="task-end-date" 
                                    name="end_date" 
                                    class="block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm transition-all duration-300"
                                >
                            </div>
                            
                            <!-- 任务描述 -->
                            <div class="md:col-span-2">
                                <label for="task-description" class="block text-sm font-medium text-gray-700 mb-1">任务描述</label>
                                <textarea 
                                    id="task-description" 
                                    name="description" 
                                    rows="3" 
                                    class="block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm transition-all duration-300"
                                ></textarea>
                            </div>
                        </div>
                        
                        <div class="flex justify-end space-x-2 mt-6">
                            <button type="button" id="cancel-add-task" class="px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400 transition">
                                取消
                            </button>
                            <button type="submit" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-blue-600 transition">
                                <i class="fas fa-save mr-2"></i>创建任务
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- 创建里程碑模态框 -->
        <div id="create-milestone-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden">
            <div class="relative top-10 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
                <div class="mt-3">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-medium text-gray-900">创建里程碑</h3>
                        <button type="button" class="text-gray-400 hover:text-gray-600" onclick="closeModal('create-milestone-modal')">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    <form id="create-milestone-form" method="post" action="/milestones/create/{{ project.id }}">
                        <input type="hidden" name="project_id" value="{{ project.id }}">
                        <div class="space-y-4">
                            <div>
                                <label for="milestone-name" class="block text-sm font-medium text-gray-700 mb-1">里程碑名称</label>
                                <input 
                                    type="text" 
                                    id="milestone-name" 
                                    name="name" 
                                    required
                                    class="block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"
                                >
                            </div>
                            
                            <div>
                                <label for="milestone-description" class="block text-sm font-medium text-gray-700 mb-1">描述</label>
                                <textarea 
                                    id="milestone-description" 
                                    name="description" 
                                    rows="3" 
                                    class="block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"
                                ></textarea>
                            </div>
                            
                            <div>
                                <label for="milestone-due-date" class="block text-sm font-medium text-gray-700 mb-1">截止日期</label>
                                <input 
                                    type="date" 
                                    id="milestone-due-date" 
                                    name="due_date" 
                                    required
                                    class="block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"
                                >
                            </div>
                        </div>
                        
                        <div class="flex justify-end space-x-2 mt-6">
                            <button type="button" onclick="closeModal('create-milestone-modal')" class="px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400 transition">
                                取消
                            </button>
                            <button type="submit" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-blue-600 transition">
                                <i class="fas fa-save mr-2"></i>创建里程碑
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- 创建周报模态框 -->
        <div id="create-weekly-report-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden">
            <div class="relative top-10 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
                <div class="mt-3">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-medium text-gray-900">创建周报</h3>
                        <button type="button" class="text-gray-400 hover:text-gray-600" onclick="closeModal('create-weekly-report-modal')">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    <form id="create-weekly-report-form" method="post" action="/weekly_report/create">
                        <input type="hidden" name="project_id" value="{{ project.id }}">
                        <div class="space-y-4">
                            <div>
                                <label for="weekly-report-start-date" class="block text-sm font-medium text-gray-700 mb-1">周开始日期</label>
                                <input 
                                    type="date" 
                                    id="weekly-report-start-date" 
                                    name="start_date" 
                                    required
                                    class="block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"
                                >
                            </div>
                            
                            <div>
                                <label for="weekly-report-end-date" class="block text-sm font-medium text-gray-700 mb-1">周结束日期</label>
                                <input 
                                    type="date" 
                                    id="weekly-report-end-date" 
                                    name="end_date" 
                                    required
                                    class="block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"
                                >
                            </div>
                            
                            <div>
                                <label for="weekly-report-work-hours" class="block text-sm font-medium text-gray-700 mb-1">工作时长(小时)</label>
                                <input 
                                    type="number" 
                                    id="weekly-report-work-hours" 
                                    name="work_hours" 
                                    min="0" 
                                    step="0.5"
                                    required
                                    class="block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"
                                >
                            </div>
                            
                            <div>
                                <label for="weekly-report-content" class="block text-sm font-medium text-gray-700 mb-1">工作内容</label>
                                <textarea 
                                    id="weekly-report-content" 
                                    name="content" 
                                    rows="5" 
                                    required
                                    class="block w-full px-3 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm"
                                ></textarea>
                            </div>
                        </div>
                        
                        <div class="flex justify-end space-x-2 mt-6">
                            <button type="button" onclick="closeModal('create-weekly-report-modal')" class="px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400 transition">
                                取消
                            </button>
                            <button type="submit" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-blue-600 transition">
                                <i class="fas fa-save mr-2"></i>创建周报
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- 删除项目确认模态框 -->
        <div id="delete-project-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden">
            <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
                <div class="mt-3 text-center">
                    <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-red-100">
                        <i class="fas fa-exclamation-triangle text-red-600"></i>
                    </div>
                    <h3 class="text-lg leading-6 font-medium text-gray-900 mt-4">删除项目</h3>
                    <div class="mt-2 px-7 py-3">
                        <p class="text-sm text-gray-500">
                            确定要删除项目 "<span id="delete-project-name"></span>" 吗?此操作不可撤销.
                        </p>
                    </div>
                    <div class="items-center px-4 py-3">
                        <form id="delete-project-form" method="post">
                            <input type="hidden" id="delete-project-id" name="project_id">
                            <button type="button" id="cancel-delete-project" class="px-4 py-2 bg-gray-300 text-gray-800 text-base font-medium rounded-md w-24 mr-2 hover:bg-gray-400">
                                取消
                            </button>
                            <button type="submit" class="px-4 py-2 bg-red-600 text-white text-base font-medium rounded-md w-24 hover:bg-red-700">
                                删除
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- 删除任务确认模态框 -->
        <div id="delete-task-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden">
            <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
                <div class="mt-3 text-center">
                    <div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-red-100">
                        <i class="fas fa-exclamation-triangle text-red-600"></i>
                    </div>
                    <h3 class="text-lg leading-6 font-medium text-gray-900 mt-4">删除任务</h3>
                    <div class="mt-2 px-7 py-3">
                        <p class="text-sm text-gray-500">
                            确定要删除任务 "<span id="delete-task-name"></span>" 吗?此操作不可撤销.
                        </p>
                    </div>
                    <div class="items-center px-4 py-3">
                        <form id="delete-task-form" method="post">
                            <input type="hidden" id="delete-task-id" name="task_id">
                            <button type="button" id="cancel-delete-task" class="px-4 py-2 bg-gray-300 text-gray-800 text-base font-medium rounded-md w-24 mr-2 hover:bg-gray-400">
                                取消
                            </button>
                            <button type="submit" class="px-4 py-2 bg-red-600 text-white text-base font-medium rounded-md w-24 hover:bg-red-700">
                                删除
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>




    </div>
</div>

<!-- Flash消息显示功能 -->
<script>
// 显示flash消息的函数
function showFlashMessage(message, type = 'success') {
    // 检查是否已存在flash消息容器
    let flashContainer = document.getElementById('flash-messages-container');
    if (!flashContainer) {
        // 创建flash消息容器
        flashContainer = document.createElement('div');
        flashContainer.id = 'flash-messages-container';
        flashContainer.className = 'fixed top-4 right-4 z-50 space-y-2';
        document.body.appendChild(flashContainer);
    }
    
    // 创建消息元素
    const messageElement = document.createElement('div');
    messageElement.className = `flash-message p-4 rounded-lg shadow-lg transform transition-all duration-300 ${
        type === 'success' ? 'bg-green-500 text-white' : 'bg-red-500 text-white'
    }`;
    
    // 添加消息内容
    messageElement.innerHTML = `
        <div class="flex items-center">
            <i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'} mr-2"></i>
            <span>${message}</span>
            <button class="ml-auto text-white hover:text-gray-200" onclick="this.parentElement.parentElement.remove()">
                <i class="fas fa-times"></i>
            </button>
        </div>
    `;
    
    // 添加到容器
    flashContainer.appendChild(messageElement);
    
    // 动画显示
    setTimeout(() => {
        messageElement.classList.add('translate-x-0');
    }, 10);
    
    // 5秒后自动隐藏
    setTimeout(() => {
        messageElement.classList.add('opacity-0', 'translate-x-full');
        setTimeout(() => {
            if (messageElement.parentNode) {
                messageElement.parentNode.removeChild(messageElement);
            }
        }, 300);
    }, 5000);
}

// 关闭模态框的函数
function closeModal(modalId) {
    document.getElementById(modalId).classList.add('hidden');
}

// 标签页切换功能
document.addEventListener('DOMContentLoaded', function() {
    // 获取所有标签页按钮和内容
    const tabButtons = document.querySelectorAll('.tab-button');
    const tabContents = document.querySelectorAll('.tab-content');
    
    // 为每个标签页按钮添加点击事件
    tabButtons.forEach(button => {
        button.addEventListener('click', function() {
            const targetTab = this.getAttribute('data-tab');
            
            // 移除所有标签页按钮的active状态
            tabButtons.forEach(btn => {
                btn.classList.remove('bg-primary', 'text-white');
                btn.classList.add('bg-gray-100', 'text-gray-700');
            });
            
            // 隐藏所有标签页内容
            tabContents.forEach(content => {
                content.classList.add('hidden');
            });
            
            // 激活当前标签页按钮
            this.classList.remove('bg-gray-100', 'text-gray-700');
            this.classList.add('bg-primary', 'text-white');
            
            // 显示当前标签页内容
            document.getElementById(targetTab + '-tab').classList.remove('hidden');
            
            // 根据标签页类型加载数据
            if (targetTab === 'milestones') {
                loadMilestones();
            } else if (targetTab === 'reports') {
                loadWeeklyReports();
            } else if (targetTab === 'health') {
                loadProjectHealth();
            }
        });
    });
    
    // 检查URL参数，如果有指定标签页，则激活该标签页
    const urlParams = new URLSearchParams(window.location.search);
    const tabParam = urlParams.get('tab');
    if (tabParam) {
        const targetButton = document.querySelector(`[data-tab="${tabParam}"]`);
        if (targetButton) {
            targetButton.click();
        }
    }
    
    // 默认加载里程碑数据（如果里程碑标签页是激活状态）
    const activeTab = document.querySelector('.tab-button.bg-primary');
    if (activeTab && activeTab.getAttribute('data-tab') === 'milestones') {
        loadMilestones();
    }
});

// 加载里程碑数据
function loadMilestones() {
    const projectId = {{ project.id }};
    const loadingElement = document.getElementById('milestones-loading');
    const emptyElement = document.getElementById('milestones-empty');
    const tbodyElement = document.getElementById('milestones-tbody');
    
    // 显示加载状态
    loadingElement.classList.remove('hidden');
    emptyElement.classList.add('hidden');
    tbodyElement.innerHTML = '';
    
    // 发送AJAX请求获取里程碑数据
    fetch(`/api/projects/${projectId}/milestones`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCsrfToken()
        }
    })
        .then(response => response.json())
        .then(data => {
            loadingElement.classList.add('hidden');
            
            // 检查数据结构
            const milestones = data.data && data.data.milestones ? data.data.milestones : [];
            
            if (milestones.length > 0) {
                // 渲染里程碑数据
                milestones.forEach(milestone => {
                    const row = document.createElement('tr');
                    
                    // 状态样式
                    let statusClass = '';
                    if (milestone.status === '已完成') {
                        statusClass = 'bg-green-100 text-green-800';
                    } else if (milestone.status === '进行中') {
                        statusClass = 'bg-blue-100 text-blue-800';
                    } else if (milestone.status === '已延期') {
                        statusClass = 'bg-red-100 text-red-800';
                    } else {
                        statusClass = 'bg-gray-100 text-gray-800';
                    }
                    
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">${milestone.name}</div>
                        </td>
                        <td class="px-6 py-4">
                            <div class="text-sm text-gray-900">${milestone.description || '-'}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">${milestone.due_date}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${statusClass}">
                                ${milestone.status}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <a href="/milestone/edit/${milestone.id}" class="text-indigo-600 hover:text-indigo-900 mr-3">编辑</a>
                            <a href="javascript:void(0)" class="text-red-600 hover:text-red-900" onclick="deleteMilestone(${milestone.id}, '${milestone.name}')">删除</a>
                        </td>
                    `;
                    
                    tbodyElement.appendChild(row);
                });
            } else {
                // 显示空数据提示
                emptyElement.classList.remove('hidden');
            }
        })
        .catch(error => {
            loadingElement.classList.add('hidden');
            console.error('加载里程碑数据失败:', error);
            showFlashMessage('加载里程碑数据失败', 'error');
        });
}

// 加载周报数据
function loadWeeklyReports() {
    const projectId = {{ project.id }};
    const loadingElement = document.getElementById('reports-loading');
    const emptyElement = document.getElementById('reports-empty');
    const tbodyElement = document.getElementById('reports-tbody');
    
    // 显示加载状态
    loadingElement.classList.remove('hidden');
    emptyElement.classList.add('hidden');
    tbodyElement.innerHTML = '';
    
    // 发送AJAX请求获取周报数据
    fetch(`/api/projects/${projectId}/weekly-reports?t=${new Date().getTime()}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCsrfToken()
        }
    })
        .then(response => response.json())
        .then(data => {
            loadingElement.classList.add('hidden');
            
            // 检查数据结构
            const reports = data.data && data.data.reports ? data.data.reports : [];
            
            if (reports.length > 0) {
                // 渲染周报数据
                reports.forEach(report => {
                    const row = document.createElement('tr');
                    
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">${report.start_date} ~ ${report.end_date}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">${report.submitter_name}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">${report.work_hours}小时</div>
                        </td>
                        <td class="px-6 py-4">
                            <div class="text-sm text-gray-900 max-w-xs truncate" title="${report.content}">${report.content}</div>
                        </td>
                        <td class="px-6 py-4">
                            <div class="text-sm text-gray-900 max-w-xs truncate" title="${report.next_plan || '-'}">${report.next_plan || '-'}</div>
                        </td>
                        <td class="px-6 py-4">
                            <div class="text-sm text-gray-900 max-w-xs truncate" title="${report.problems || '-'}">${report.problems || '-'}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <a href="/weekly_report/edit/${report.id}" class="text-indigo-600 hover:text-indigo-900 mr-3">编辑</a>
                            <a href="javascript:void(0)" class="text-red-600 hover:text-red-900" onclick="deleteWeeklyReport(${report.id})">删除</a>
                        </td>
                    `;
                    
                    tbodyElement.appendChild(row);
                });
            } else {
                // 显示空数据提示
                emptyElement.classList.remove('hidden');
            }
        })
        .catch(error => {
            loadingElement.classList.add('hidden');
            console.error('加载周报数据失败:', error);
            showFlashMessage('加载周报数据失败', 'error');
        });
}

// 加载项目健康度数据
function loadProjectHealth() {
    const projectId = {{ project.id }};
    
    // 发送AJAX请求获取项目健康度数据
    fetch(`/api/projects/${projectId}/health?t=${new Date().getTime()}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCsrfToken()
        }
    })
        .then(response => response.json())
        .then(data => {
            // 检查数据结构
            const healthData = data.data ? data.data : {};
            
            // 更新健康度评分
            const healthScore = healthData.health_score || 0;
            document.getElementById('health-score').textContent = healthScore;
            
            // 更新健康度状态
            let healthStatus = '';
            if (healthScore >= 80) {
                healthStatus = '良好';
                document.getElementById('health-circle').setAttribute('stroke', '#10b981');
            } else if (healthScore >= 60) {
                healthStatus = '一般';
                document.getElementById('health-circle').setAttribute('stroke', '#f59e0b');
            } else {
                healthStatus = '较差';
                document.getElementById('health-circle').setAttribute('stroke', '#ef4444');
            }
            document.getElementById('health-status').textContent = healthStatus;
            
            // 更新健康度圆形进度条
            const circumference = 2 * Math.PI * 56;
            const offset = circumference - (healthScore / 100) * circumference;
            document.getElementById('health-circle').setAttribute('stroke-dashoffset', offset);
            
            // 更新各项指标
            document.getElementById('delay-days').textContent = (healthData.delay_days || 0) + '天';
            document.getElementById('task-completion').textContent = (healthData.task_completion || 0) + '%';
            document.getElementById('milestone-completion').textContent = (healthData.milestone_completion || 0) + '%';
            document.getElementById('cost-usage').textContent = (healthData.cost_usage || 0) + '%';
            
            // 更新风险提示
            const riskAlerts = document.getElementById('risk-alerts');
            const noRisks = document.getElementById('no-risks');
            
            const risks = healthData.risks || [];
            if (risks.length > 0) {
                riskAlerts.innerHTML = '';
                risks.forEach(risk => {
                    const riskItem = document.createElement('div');
                    
                    let riskClass = '';
                    if (risk.level === '高') {
                        riskClass = 'bg-red-50 border-l-4 border-red-400 p-4';
                    } else if (risk.level === '中') {
                        riskClass = 'bg-yellow-50 border-l-4 border-yellow-400 p-4';
                    } else {
                        riskClass = 'bg-blue-50 border-l-4 border-blue-400 p-4';
                    }
                    
                    riskItem.className = riskClass;
                    riskItem.innerHTML = `
                        <div class="flex">
                            <div class="flex-shrink-0">
                                <i class="fas ${risk.level === '高' ? 'fa-exclamation-triangle text-red-400' : risk.level === '中' ? 'fa-exclamation-circle text-yellow-400' : 'fa-info-circle text-blue-400'}"></i>
                            </div>
                            <div class="ml-3">
                                <p class="text-sm text-gray-700">
                                    <span class="font-medium">${risk.title}:</span> ${risk.description}
                                </p>
                            </div>
                        </div>
                    `;
                    
                    riskAlerts.appendChild(riskItem);
                });
                noRisks.classList.add('hidden');
            } else {
                riskAlerts.innerHTML = '';
                noRisks.classList.remove('hidden');
            }
            
            // 初始化健康度趋势图表
            initHealthTrendChart(data.trend_data);
        })
        .catch(error => {
            console.error('加载项目健康度数据失败:', error);
            showFlashMessage('加载项目健康度数据失败', 'error');
        });
}

// 初始化健康度趋势图表
function initHealthTrendChart(trendData) {
    const chartElement = document.getElementById('health-trend-chart');
    
    // 如果没有ECharts库，则跳过图表初始化
    if (typeof echarts === 'undefined') {
        console.warn('ECharts库未加载，无法显示健康度趋势图表');
        return;
    }
    
    // 初始化ECharts实例
    const chart = echarts.init(chartElement);
    
    // 准备图表数据
    const dates = trendData ? trendData.map(item => item.date) : [];
    const scores = trendData ? trendData.map(item => item.score) : [];
    
    // 配置图表选项
    const option = {
        tooltip: {
            trigger: 'axis'
        },
        xAxis: {
            type: 'category',
            data: dates
        },
        yAxis: {
            type: 'value',
            min: 0,
            max: 100
        },
        series: [{
            data: scores,
            type: 'line',
            smooth: true,
            lineStyle: {
                color: '#3b82f6'
            },
            itemStyle: {
                color: '#3b82f6'
            },
            areaStyle: {
                color: {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [{
                        offset: 0, color: 'rgba(59, 130, 246, 0.3)'
                    }, {
                        offset: 1, color: 'rgba(59, 130, 246, 0.1)'
                    }]
                }
            }
        }]
    };
    
    // 应用配置
    chart.setOption(option);
    
    // 响应窗口大小变化
    window.addEventListener('resize', function() {
        chart.resize();
    });
}

// 删除里程碑
function deleteMilestone(id, name) {
    if (confirm(`确定要删除里程碑 "${name}" 吗？此操作不可撤销。`)) {
        fetch(`/milestone/delete/${id}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showFlashMessage('里程碑删除成功');
                loadMilestones(); // 重新加载里程碑数据
            } else {
                showFlashMessage('里程碑删除失败: ' + (data.message || '未知错误'), 'error');
            }
        })
        .catch(error => {
            console.error('删除里程碑失败:', error);
            showFlashMessage('里程碑删除失败', 'error');
        });
    }
}

// 删除周报
function deleteWeeklyReport(id) {
    if (confirm('确定要删除这条周报吗？此操作不可撤销。')) {
        fetch(`/weekly_report/delete/${id}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showFlashMessage('周报删除成功');
                loadWeeklyReports(); // 重新加载周报数据
            } else {
                showFlashMessage('周报删除失败: ' + (data.message || '未知错误'), 'error');
            }
        })
        .catch(error => {
            console.error('删除周报失败:', error);
            showFlashMessage('周报删除失败', 'error');
        });
    }
}
</script>

{% endblock content %}